<template>
  <div class="users-list">
    <div class="page-header">
      <h2>客户档案管理</h2>
      <div class="button-group">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0" v-if="authStore.userRole !== '用户'">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd" v-if="authStore.userRole !== '用户'">
          <el-icon><Plus /></el-icon>
          添加客户
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户姓名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="userId" label="客户编号" width="100" />
        <el-table-column prop="username" label="客户姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="tel" label="固定电话" width="120" />
        <el-table-column prop="email" label="电子邮箱" width="180" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="hobby" label="客户偏好" min-width="150" show-overflow-tooltip />
        <el-table-column prop="userNotes" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" v-if="authStore.userRole !== '用户'">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { usersApi } from '@/api'
import type { Users, UsersQuery } from '@/types'
import { handlePageResponse } from '@/utils/pagination'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const tableData = ref<Users[]>([])
const selectedIds = ref<number[]>([]) // 存储选中的客户ID
const searchForm = reactive<Omit<UsersQuery, 'pageNum' | 'pageSize'>>({
  userName: '',
  phone: '',
  email: ''
})

const pagination = reactive({
  current: 1,
  size: 5,
  total: 0
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params: UsersQuery = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    
    const response = await usersApi.getPage(params)
    const pageData = handlePageResponse<Users>(response)
    
    tableData.value = pageData.records
    pagination.total = pageData.total
    // 清空选中项
    selectedIds.value = []
  } catch (error) {
    console.error('获取客户数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理选中项变化
const handleSelectionChange = (selection: Users[]) => {
  selectedIds.value = selection.map(item => item.userId!)
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条客户记录吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await usersApi.batchDelete(selectedIds.value)
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      fetchData() // 重新加载数据
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    phone: '',
    email: ''
  })
  pagination.current = 1
  fetchData()
}

// 添加客户
const handleAdd = () => {
  router.push('/users/add')
}

// 编辑客户
const handleEdit = (row: Users) => {
  router.push(`/users/update/${row.userId}`)
}

// 删除客户
const handleDelete = async (row: Users) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户"${row.username}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await usersApi.delete(row.userId!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  fetchData()
})

// 监听分页参数变化
watch(
  () => [pagination.current, pagination.size],
  () => {
    fetchData()
  }
)
</script>

<style scoped>
.users-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.button-group {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>